package com.tp.service;

import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.jfinal.plugin.activerecord.Page;
import com.tp.base.BaseService;
import com.tp.base.Paginator;
import com.tp.model.sys.SysAuth;
import com.tp.model.sys.SysAuthUser;
import com.tp.utils.DateUtils;
import com.tp.utils.SQLUtils;
import com.tp.utils.StrUtils;
import javolution.util.FastList;
import javolution.util.FastMap;

/**
 * 权限service
 * 
 * @author TP
 *
 */
public class AuthService extends BaseService {

	private static SysAuth sa = new SysAuth().dao();
	private static SysAuthUser sau = new SysAuthUser().dao();
	
	/**
	 * 分页查询
	 * @param model
	 * @param orderBy
	 * @param paginator
	 * @return
	 */
	public Page<SysAuth> getPageByWhere(SysAuth model, String orderBy, Paginator paginator) {
		SQLUtils sql = new SQLUtils("from " + SysAuth.tableName + " t where 1=1");
		if (model.getAttrValues().length != 0) {
			sql.setAlias("t");
			// 查询条件
			 // 查询条件
            String isHalt = model.getStr("is_halt");
            if (!StrUtils.isEmpty(isHalt) && !"-1".equals(isHalt)) {
                sql.whereEquals("is_halt", isHalt);
            }
            String descript = model.getStr("descript");
            if (!StrUtils.isEmpty(descript)) {
                sql.whereLike("descript", descript);
            }
		}
		if (StrUtils.isEmpty(orderBy)) {
			sql.append(" order by t.id desc");
		} else {
			sql.append(" order by ").append(orderBy);
		}
		Page<SysAuth> page = sa.paginate(paginator, "select t.*", sql.toString());
		return page;
	}
	
	/**
	 * 删除权限
	 * @param ids
	 * @param uid
	 * @return
	 */
	public boolean deleteObject(String[] ids, Integer uid) {
		if (!StrUtils.empty(ids)) {
			boolean flag = false;
			for (String id : ids) {
				SysAuth model = new SysAuth();
				model.put("update_id", uid);
				model.put("update_time", DateUtils.getNow(DateUtils.DEFAULT_REGEX_YYYY_MM_DD_HH_MIN_SS));
				flag = model.deleteById(id);
				if (!flag) {
					break;
				}
			}
			return flag;
		}
		return false;
	}
	
	/**
	 * 查询配置权限
	 * @param isHalt
	 * @return
	 */
	public String getAuthList(String isHalt){
		List<SysAuth> list = sa.findByWhere("where is_halt=? order by id desc", isHalt);
		List<Map<String, Object>> listMap = FastList.newInstance();
		for (SysAuth itme : list) {
			Map<String, Object> temp = FastMap.newInstance();
			temp.put("value", itme.getStr("id"));
			temp.put("title", itme.getUrl() + " -- " +  itme.getDescript());
			listMap.add(temp);
		}
		return JSON.toJSONString(listMap);
	}
	
	/**
	 * 查询用户权限
	 * @param uid
	 * @return
	 */
	public String getUserAuthId(int uid){
		String authIds = "";
		SysAuthUser auser = sau.findFirstByWhere("where user_id=?", uid);
		if(!StrUtils.empty(auser)){
			authIds = auser.getUrlAuth();
		}
		return authIds;
	}
	
	
}
